package com.kevin.controller.controller.system;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.kevin.common.api.R;
import com.kevin.common.storage.AliyunStorageProperties;
import com.kevin.common.storage.StorageService;
import com.kevin.common.storage.SysFileUploadVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 文件上传
 *
 * @author 阿沐 babamu@126.com
 */
@RestController
@RequestMapping("sys/file")
@Api(tags = "文件上传")
@AllArgsConstructor
public class SysFileUploadController {
    private final StorageService storageService;

    @PostMapping("upload")
    @ApiOperation(value = "上传")
    public R<SysFileUploadVO> upload(@ApiParam(value = "file", allowMultiple = true) @RequestPart("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return R.failed("请选择需要上传的文件");
        }

        // 上传路径
        String path = storageService.getPath(IdUtil.fastSimpleUUID() + "." + FileUtil.getSuffix(file.getOriginalFilename()));
        // 上传文件
        String url = storageService.upload(file.getBytes(), path);

        SysFileUploadVO vo = new SysFileUploadVO();
        vo.setUrl(url);
        vo.setSize(file.getSize());
        vo.setName(file.getOriginalFilename());
        vo.setPlatform(storageService.properties.getConfig().getType().name());

        return R.ok(vo);
    }

    @GetMapping("download")
    @ApiOperation(value = "下载")
    public void upload(@RequestParam("name") String name, HttpServletResponse response) throws IOException {
        AliyunStorageProperties props = storageService.properties.getAliyun();
        Assert.notNull(props, "未开启文件系统!");
        response.sendRedirect(props.getDomain() + name);
//        File file = new File(props.getPath() + File.separator + name);
//        Assert.isTrue(file.exists(), "file not exist!");
//        response.setHeader("Content-Type", ViewContentType.getContentType(name));
//        response.addHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
//        try (ServletOutputStream outputStream = response.getOutputStream();) {
//            outputStream.write(FileUtil.readBytes(file));
//            outputStream.flush();
//        }
    }
}
